package com.blkj.modular.admin.controller;

import com.blkj.common.core.bean.R;
import com.blkj.common.core.entity.UserEntity;
import com.blkj.common.exception.user.AccountOrPassNotMatchException;
import com.blkj.common.exception.user.UserBlockedException;
import com.blkj.common.exception.user.UserNotExistsException;
import com.blkj.common.utils.StringUtils;
import com.blkj.common.utils.security.Md5Utils;
import com.blkj.modular.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    UserService userService;

    @RequestMapping({"","index"})
    public String adminIndex(){
        return "admin/index";
    }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String loginPage(HttpServletRequest request){
        Object user = request.getSession().getAttribute("user");
        if (null != user){
            return "redirect:/admin";
        }
        return "admin/login";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public R login(UserEntity userEntity, HttpServletRequest request){
        UserEntity loginUser = userService.getUserByUsername(userEntity.getUsername());
        String hash = Md5Utils.hash(userEntity.getPassword());

        if (null == loginUser){
            throw new UserNotExistsException();
        }

        if (!loginUser.getPassword().equals(hash)){
            throw new AccountOrPassNotMatchException();
        }

        if (loginUser.getStatus()==0){
            throw new UserBlockedException();
        }

        request.getSession().setAttribute("user",loginUser);
        request.getSession().setAttribute("role","admin");

        String lastUrl = (String) request.getSession().getAttribute("lastUrl");

        Map<String,Object> data = new HashMap<>();
        if (lastUrl!=null && !StringUtils.isEmpty(lastUrl)){
            data.put("url",lastUrl);
        }

        return R.ok().data(data);
    }

    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("user");
        response.sendRedirect("/");
    }

}
